package com.xiaobai.netease_news.adapters;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.toolbox.ImageLoader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.xiaobai.netease_news.R;
import com.xiaobai.netease_news.activities.VideoDetailActivity;
import com.xiaobai.netease_news.client.VideoListenerAPI;
import com.xiaobai.netease_news.model.Video;
import com.xiaobai.netease_news.utils.ImageLoadTask;
import com.xiaobai.netease_news.utils.RequestManager;

import java.lang.ref.WeakReference;
import java.util.List;

import javax.annotation.security.RunAs;

/**
 * Created by PiscesQ on 2015/6/25.
 */
public class VideoAdapter extends BaseAdapter {

    private static final int STATUS_NORMAL = 1;
    private static final int STATUS_PLAY = 2;


    private Context context;
    private List<Video> videoList;
    private int resourceId;

    private String mp4Url;
    private boolean isThreadEnd = false;

    private int playStatus = STATUS_NORMAL;
    private int clickPosition = -1;
    private String clickUrl;
    private ViewHolder currentHolder;
    private VideoListenerAPI controllerInstance;
    private ProgressBar currentProgressBar;
    private TextView currentPosition;

    private MyHandler handler = new MyHandler(this);

    public VideoAdapter(Context context, List<Video> videoList, int resourceId) {
        this.context = context;
        this.videoList = videoList;
        this.resourceId = resourceId;
    }

    public void setVideoList(List<Video> videoList) {
        this.videoList = videoList;
    }

    public void addVideoList(List<Video> newList) {
        this.videoList.addAll(newList);
    }

    @Override
    public int getCount() {
        int ret = 0;
        if (videoList != null) {
            ret = videoList.size();
        }
        return ret;
    }

    @Override
    public Object getItem(int position) {
        Object ret = null;
        if (videoList != null) {
            ret = videoList.get(position);
        }
        return ret;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        View ret = null;
        ViewHolder holder = null;

        Log.d("VideoAdapter", "1 position---" + position);

        if (convertView == null) {
            ret = LayoutInflater.from(context).inflate(resourceId, null);
        } else {
            ret = convertView;
        }
        holder = (ViewHolder) ret.getTag();
        if (holder == null) {
            holder = new ViewHolder();
            holder.videoImage = (SimpleDraweeView) ret.findViewById(R.id.item_video_image);
            holder.videoTitle = (TextView) ret.findViewById(R.id.item_video_title);
            holder.videoTime = (TextView) ret.findViewById(R.id.item_video_time);
            holder.videoPlayCount = (TextView) ret.findViewById(R.id.item_video_play_count);
            holder.videoComment = (TextView) ret.findViewById(R.id.item_video_comment);
            holder.videoView = (VideoView) ret.findViewById(R.id.item_video_videoview);

            //获得控制器
            holder.videoController = (ViewGroup) ret.findViewById(R.id.item_video_controller);

            //获得进度条
            holder.videoProgressBar = (ProgressBar) ret.findViewById(R.id.item_video_progress);

            ret.setTag(holder);
        }

        //获得播放图标
        ImageView imgPlay = (ImageView) ret.findViewById(R.id.item_video_play);
        //播放信息布局RelativeLayout
        RelativeLayout relativeLayout = (RelativeLayout) ret.findViewById(R.id.item_video_content);

        //设置图片播放点击事件的监听
        imgPlay.setOnClickListener(new OnImagePlayClickListener(position, holder, parent));
        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击此处，跳转的视频详情页面
                Intent intent = new Intent(context, VideoDetailActivity.class);

                context.startActivity(intent);
            }
        });

        //加载时默认处理成隐藏
        holder.videoView.setVisibility(View.GONE);
        holder.videoProgressBar.setVisibility(View.GONE);
        holder.videoController.setVisibility(View.GONE);
        holder.videoImage.setVisibility(View.VISIBLE);

        //视频播放
        playVideo(position, holder);

        //更新控件信息
        setItemInformation(position, holder);

        return ret;
    }

    /**
     * 更新每个条目的信息
     * @param position
     * @param holder
     */
    private void setItemInformation(int position, ViewHolder holder) {
        Video video = videoList.get(position);
        if (video != null) {
            String cover = video.getCover();
            if (cover != null) {
                holder.videoImage.setImageBitmap(null);
                holder.videoImage.setTag(cover);
//                ImageLoader imageLoader = RequestManager.getInstance(context).getImageLoader();
//                imageLoader.get(cover,imageLoader.getImageListener(holder.videoImage, R.mipmap.ic_launcher, R.mipmap.ic_launcher));
                holder.videoImage.setImageURI(Uri.parse(cover));

            }

            //获得视频mp4路径
            mp4Url = video.getMp4Url();

            //获得标题
            String title = video.getTitle();
            holder.videoTitle.setText(title);

            int timeLength = video.getLength();

            holder.videoTime.setText(formatTime(timeLength));

            int playCount = video.getPlayCount();
            holder.videoPlayCount.setText("" + playCount);

            int replyCount = video.getReplyCount();
            holder.videoComment.setText("");
            if (replyCount > 0) {
                holder.videoComment.setText(replyCount + "跟帖");
            }
        }
    }

    /**
     * 视频播放
     * @param position
     * @param holder
     */
    private void playVideo(int position, ViewHolder holder) {
        if (playStatus == STATUS_PLAY && clickPosition == position) {    //判断播放状态和点击位置

            Toast.makeText(context, "VideoView加载。。。", Toast.LENGTH_SHORT).show();
            //显示VideoView和进度条
            holder.videoView.setVisibility(View.VISIBLE);
            holder.videoProgressBar.setVisibility(View.VISIBLE);

            //播放模式中隐藏cover图片
            holder.videoImage.setVisibility(View.INVISIBLE);

            //设置视频Uri，并播放视频
            Uri uri = Uri.parse(clickUrl);
            holder.videoView.setVideoURI(uri);
            holder.videoView.start();

//            //添加视频控制器
//            MediaController controller = new MediaController(context);
//            controller.show();
//            holder.videoView.setMediaController(controller);

            //获得自定义视频控制器中相应的控件
            TextView btnClose = (TextView) currentHolder.videoController.findViewById(R.id.video_controller_close);
            ImageButton btnPlay = (ImageButton) currentHolder.videoController.findViewById(R.id.video_controller_play);

            ImageButton btnFullScreen = (ImageButton) currentHolder.videoController.findViewById(R.id.video_controller_btn_full_screen);
            Button btnDanmu = (Button) currentHolder.videoController.findViewById(R.id.video_controller_btn_danmu);
            currentPosition = (TextView) currentHolder.videoController.findViewById(R.id.video_controller_current_position);
            currentProgressBar = (ProgressBar) currentHolder.videoController.findViewById(R.id.video_controller_progress);

            //启动线程更新进度条和当前播放位置
            Thread updateProgressThread = new Thread(new ProgressUpdate());
            updateProgressThread.start();

            controllerInstance = VideoListenerAPI.getSingleInstance();
//            controllerInstance.setView(currentHolder.videoView);

            //点击关闭按钮，监听操作
            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    resetStatus();
                }
            });
            btnPlay.setOnClickListener(controllerInstance.getPlayOnClickListener(btnPlay, currentHolder.videoView));
            btnFullScreen.setOnClickListener(controllerInstance.getFullScreenOnClickListener(btnFullScreen));


            //视频播放完成的监听事件
            holder.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Toast.makeText(context, "视频播放完成！", Toast.LENGTH_SHORT).show();
                    //修改playStatus 为 STATUS_NORMAL
                    resetStatus();
                }
            });

            //视频准备完成监听事件
            holder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Toast.makeText(context, "视频准备完成！", Toast.LENGTH_SHORT).show();
                    videoPrepared();
                }
            });
        }
    }

    /**
     * 状态重置
     */
    private void resetStatus() {
        playStatus = STATUS_NORMAL;
        isThreadEnd = true;
        currentHolder.videoView.setVisibility(View.GONE);
        currentHolder.videoImage.setVisibility(View.VISIBLE);
        //视频播放完成，重置数据
        clickPosition = -1;
        currentHolder.videoController.setVisibility(View.GONE);
        currentHolder = null;
        clickUrl = null;
        currentPosition.setText("00:00");
        currentProgressBar.setProgress(0);
    }

    /**
     * 视频准备完成
     */
    private void videoPrepared() {
        currentHolder.videoProgressBar.setVisibility(View.GONE);
        currentHolder.videoController.setVisibility(View.GONE);
        currentHolder.videoView.start();
        currentHolder.videoController.setVisibility(View.VISIBLE);

        TextView txtDuration = (TextView) currentHolder.videoController.findViewById(R.id.video_controller_duration);

        //设置进度条最大值
        int duration = currentHolder.videoView.getDuration();
        currentProgressBar.setMax(duration);

        //设置视频时长
        int length = videoList.get(clickPosition).getLength();
        txtDuration.setText(formatTime(length));
    }

    /**
     * 单条刷新
     *
     * @param listView
     * @param itemData
     */
    private void updateSingleRow(ListView listView, Object itemData) {

        if (listView != null) {
            int start = listView.getFirstVisiblePosition();
            for (int i = start, j = listView.getLastVisiblePosition(); i < j; i++) {
//                Log.d("VideoAdapter","id:"+id+"   itemId:"+itemPosition);
                Log.d("VideoAdapter", "============ j:" + j);
                Log.d("VideoAdapter", "getItemAtPosition :" + listView.getItemAtPosition(i));
//                Log.d("VideoAdapter","position:"+position+"   clickPosition:"+clickPosition+"   i:"+i);
                Log.d("VideoAdapter", "clickPosition:" + clickPosition + "   i:" + i);
                if (listView.getItemAtPosition(i+1).equals(itemData)) {
                    Toast.makeText(context, "单条更新....", Toast.LENGTH_SHORT).show();
                    Log.d("VideoAdapter", "单条更新--clickPosition:" + clickPosition + "   i:" + i);
                    View view = listView.getChildAt(i - start);
                    getView(i, view, listView);
                    break;
                }
            }
        }
    }

    /**
     * 格式化时长
     *
     * @param timeLength
     * @return
     */
    private String formatTime(int timeLength) {
        String ret = null;

        String minute = Integer.toString(timeLength / 60);
        String second = Integer.toString(timeLength % 60);
        ret = minute + ":" + (second.length() > 1 ? second : "0" + second);

        return ret;
    }

    public class MyHandler extends Handler {
        private final WeakReference<BaseAdapter> adapter;

        public MyHandler(BaseAdapter adapter) {
            this.adapter = new WeakReference<>(adapter);
        }

        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 1:
                    int pos = msg.arg1;
                    currentProgressBar.setProgress(pos);
                    currentPosition.setText(formatTime(pos/1000));
                    break;
            }
        }
    }

    public class OnImagePlayClickListener implements View.OnClickListener{

        private int position;
        private ViewHolder holder;
        private ViewGroup parent;

        public OnImagePlayClickListener(int position, ViewHolder viewHolder, ViewGroup parent){
            this.position = position;
            this.holder = viewHolder;
            this.parent = parent;
        }


        @Override
        public void onClick(View v) {
            if (clickPosition != position) {
                clickPosition = position;
                currentHolder = holder;
                Log.d("VideoAdapter", "onClick finalPosition---" + position);
                playStatus = STATUS_PLAY;
                Video video = videoList.get(position);
                clickUrl = video.getMp4Url();

                // 获取点击的view
                int firstVisiblePosition = ((ListView) parent).getFirstVisiblePosition();
                View view = parent.getChildAt(position - firstVisiblePosition);
                Log.d("VideoAdapter","getChildAt : = "+view);
                if (view != null) {
                    VideoView videoView = (VideoView) view.findViewById(R.id.item_video_videoview);
                    Log.d("VideoAdapter","getChildAt : "+videoView);
                }

//                updateSingleRow((ListView) parent, video);//更新数据，重新加载单个条目
                notifyDataSetChanged();//更新数据，重新加载每个条目
            } else {
                Toast.makeText(context, "再次点击同一条目。。", Toast.LENGTH_SHORT).show();
                //再次点击同一视频，弹出控制条
                //currentHolder.videoView.stopPlayback();

                VideoView videoView = currentHolder.videoView;
                ViewGroup videoController = currentHolder.videoController;

                if (videoView.getVisibility() == View.VISIBLE) {
                    if (videoController.getVisibility() != View.VISIBLE) {
                        videoController.setVisibility(View.VISIBLE);
                    } else {
                        videoController.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    /**
     * 进度更新线程
     */
    public class ProgressUpdate implements Runnable{

        @Override
        public void run() {
            isThreadEnd = false;
            while (!isThreadEnd) {
                int pos = -1;
                if (currentHolder != null) {
                    pos = currentHolder.videoView.getCurrentPosition();
                }
                Message msg = handler.obtainMessage(1);
                msg.arg1 = pos;
                handler.sendMessage(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 缓存类
     */
    private static class ViewHolder {
        public SimpleDraweeView videoImage;
        public VideoView videoView;
        public ProgressBar videoProgressBar;
        public TextView videoTitle;
        public TextView videoTime;
        public TextView videoPlayCount;
        public TextView videoComment;

        public ViewGroup videoController;
    }

    /////////////////////////////////////////////////////////////////////////////////////////
    //多布局显示需要使用的方法

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public int getViewTypeCount() {
        return super.getViewTypeCount();
    }
}

